<template>
    <div class="test-upload">
        <h2>深加工信息图片上传/删除调试</h2>

        <div class="test-section">
            <h3>测试参数</h3>
            <el-form :model="testForm" label-width="120px">
                <el-form-item label="溯源ID：">
                    <el-input v-model="testForm.traceabilityId" placeholder="请输入溯源ID" />
                </el-form-item>
                <el-form-item label="字段类型：">
                    <el-select v-model="testForm.fieldType" placeholder="请选择字段类型">
                        <el-option label="食品安全信息" value="Enterprise_Image" />
                        <el-option label="原料相关材料" value="Raw_Material" />
                        <el-option label="辅料相关材料" value="Auxiliary_Materials" />
                        <el-option label="添加剂相关材料" value="Additive_Materials" />
                        <el-option label="包材相关材料" value="Packaging_Materials" />
                        <el-option label="企业照片" value="Certification_Documents" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>

        <div class="test-section">
            <h3>文件上传测试</h3>
            <el-form-item label="选择文件：">
                <input type="file" ref="fileInput" @change="handleFileSelect" accept="image/*" />
            </el-form-item>
            <el-button @click="testUpload" :disabled="!selectedFile">测试上传</el-button>
            <el-button @click="testFileValidation" :disabled="!selectedFile">测试文件验证</el-button>
        </div>

        <div class="test-section">
            <h3>图片显示测试</h3>
            <div class="image-display-test">
                <div class="test-item">
                    <h4>食品安全信息</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.foodSafety" :key="index" class="image-item">
                            <img :src="url" :alt="`食品安全信息${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Enterprise_Image')">删除</el-button>
                        </div>
                    </div>
                </div>

                <div class="test-item">
                    <h4>原料相关材料</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.rawMaterial" :key="index" class="image-item">
                            <img :src="url" :alt="`原料相关材料${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Raw_Material')">删除</el-button>
                        </div>
                    </div>
                </div>

                <div class="test-item">
                    <h4>辅料相关材料</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.auxiliaryMaterial" :key="index" class="image-item">
                            <img :src="url" :alt="`辅料相关材料${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Auxiliary_Materials')">删除</el-button>
                        </div>
                    </div>
                </div>

                <div class="test-item">
                    <h4>添加剂相关材料</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.additive" :key="index" class="image-item">
                            <img :src="url" :alt="`添加剂相关材料${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Additive_Materials')">删除</el-button>
                        </div>
                    </div>
                </div>

                <div class="test-item">
                    <h4>包材相关材料</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.packagingMaterial" :key="index" class="image-item">
                            <img :src="url" :alt="`包材相关材料${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Packaging_Materials')">删除</el-button>
                        </div>
                    </div>
                </div>

                <div class="test-item">
                    <h4>企业照片</h4>
                    <div class="image-list">
                        <div v-for="(url, index) in testImages.enterprisePhoto" :key="index" class="image-item">
                            <img :src="url" :alt="`企业照片${index + 1}`" />
                            <div class="image-info">{{ url }}</div>
                            <el-button size="small" @click="testDelete(url, 'Certification_Documents')">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="test-section">
            <h3>API测试</h3>
            <el-button @click="testAPI">测试API连接</el-button>
            <el-button @click="testPictureData">测试图片数据获取</el-button>
            <el-button @click="clearLogs">清空日志</el-button>
            <div class="log-container">
                <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
                    <span class="log-time">{{ log.time }}</span>
                    <span class="log-message">{{ log.message }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Read } from '@/components/Http/axiosHepler';
import { uploadImage, deleteImage } from '@/utils/uploadHelper';
import { validateImageFile } from '@/config/upload';

const testForm = reactive({
    traceabilityId: '1',
    fieldType: 'Enterprise_Image'
});

const testImages = reactive({
    foodSafety: [] as string[],
    rawMaterial: [] as string[],
    auxiliaryMaterial: [] as string[],
    additive: [] as string[],
    packagingMaterial: [] as string[],
    enterprisePhoto: [] as string[]
});

const logs = ref<Array<{ time: string, message: string, type: string }>>([]);
const selectedFile = ref<File | null>(null);

const addLog = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
    const time = new Date().toLocaleTimeString();
    logs.value.push({ time, message, type });
    console.log(`[${time}] ${message}`);
};

const handleFileSelect = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        selectedFile.value = target.files[0];
        addLog(`选择文件: ${selectedFile.value.name}`, 'info');
    }
};

const testFileValidation = () => {
    if (!selectedFile.value) {
        addLog('请先选择文件', 'error');
        return;
    }

    addLog('开始文件验证测试...', 'info');
    const validation = validateImageFile(selectedFile.value);

    if (validation.valid) {
        addLog('✅ 文件验证通过', 'success');
    } else {
        addLog(`❌ 文件验证失败: ${validation.message}`, 'error');
    }
};

const testUpload = async () => {
    if (!selectedFile.value) {
        addLog('请先选择文件', 'error');
        return;
    }

    if (!testForm.traceabilityId) {
        addLog('请输入溯源ID', 'error');
        return;
    }

    addLog('开始上传测试...', 'info');
    addLog(`文件信息: ${selectedFile.value.name}, 类型: ${selectedFile.value.type}, 大小: ${(selectedFile.value.size / 1024 / 1024).toFixed(2)}MB`, 'info');

    try {
        const url = await uploadImage(
            selectedFile.value,
            (data, file) => {
                addLog('✅ 上传成功', 'success');
                addLog(`返回URL: ${data.url || data.data?.uploadedUrls?.[0]}`, 'info');
            },
            (error) => {
                addLog(`❌ 上传失败: ${error.message}`, 'error');
            },
            parseInt(testForm.traceabilityId),
            testForm.fieldType
        );

        if (url) {
            addLog(`上传成功，URL: ${url}`, 'success');
            // 刷新图片数据
            await testPictureData();
        }
    } catch (error: any) {
        addLog(`上传异常: ${error.message}`, 'error');
    }
};

const testDelete = async (imageUrl: string, fieldType: string) => {
    addLog(`开始删除测试: ${imageUrl}`, 'info');

    try {
        const success = await deleteImage(
            parseInt(testForm.traceabilityId),
            fieldType,
            imageUrl
        );

        if (success) {
            addLog('✅ 删除成功', 'success');
            // 刷新图片数据
            await testPictureData();
        } else {
            addLog('❌ 删除失败', 'error');
        }
    } catch (error: any) {
        addLog(`删除异常: ${error.message}`, 'error');
    }
};

const testAPI = async () => {
    try {
        addLog('开始测试API连接...', 'info');

        const response = await Read.get('/Image/PictureShow', {
            params: { TraceabilityId: testForm.traceabilityId }
        });

        addLog(`API连接成功，状态码: ${response.status}`, 'success');
        addLog(`响应数据: ${JSON.stringify(response.data)}`, 'info');

    } catch (error: any) {
        addLog(`API连接失败: ${error.message}`, 'error');
        if (error.code === 'ECONNREFUSED') {
            addLog('服务器未运行或端口不正确', 'error');
        }
    }
};

const testPictureData = async () => {
    try {
        addLog('开始测试图片数据获取...', 'info');

        const response = await Read.get('/Image/PictureShow', {
            params: { TraceabilityId: testForm.traceabilityId }
        });

        if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
            const pictureData = response.data.data[0];
            addLog('获取图片数据成功', 'success');
            addLog(`图片数据字段: ${Object.keys(pictureData).join(', ')}`, 'info');

            // 更新测试图片数组 - 使用实际的数据库字段名（小写）
            testImages.foodSafety = pictureData.enterprise_Image ?
                pictureData.enterprise_Image.split(',').filter((url: string) => url && url.trim()) : [];
            testImages.rawMaterial = pictureData.raw_Material ?
                pictureData.raw_Material.split(',').filter((url: string) => url && url.trim()) : [];
            testImages.auxiliaryMaterial = pictureData.auxiliary_Materials ?
                pictureData.auxiliary_Materials.split(',').filter((url: string) => url && url.trim()) : [];
            testImages.additive = pictureData.additive_Materials ?
                pictureData.additive_Materials.split(',').filter((url: string) => url && url.trim()) : [];
            testImages.packagingMaterial = pictureData.packaging_Materials ?
                pictureData.packaging_Materials.split(',').filter((url: string) => url && url.trim()) : [];
            testImages.enterprisePhoto = pictureData.certification_Documents ?
                pictureData.certification_Documents.split(',').filter((url: string) => url && url.trim()) : [];

            addLog(`食品安全信息图片数量: ${testImages.foodSafety.length}`, 'info');
            addLog(`原料相关材料图片数量: ${testImages.rawMaterial.length}`, 'info');
            addLog(`辅料相关材料图片数量: ${testImages.auxiliaryMaterial.length}`, 'info');
            addLog(`添加剂相关材料图片数量: ${testImages.additive.length}`, 'info');
            addLog(`包材相关材料图片数量: ${testImages.packagingMaterial.length}`, 'info');
            addLog(`企业照片数量: ${testImages.enterprisePhoto.length}`, 'info');

        } else {
            addLog('没有找到图片数据', 'error');
        }

    } catch (error: any) {
        addLog(`获取图片数据失败: ${error.message}`, 'error');
    }
};

const clearLogs = () => {
    logs.value = [];
};
</script>

<style scoped>
.test-upload {
    padding: 24px;
    max-width: 1200px;
    margin: 0 auto;
}

.test-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.test-section h3 {
    margin-top: 0;
    margin-bottom: 16px;
    color: #303133;
}

.image-display-test {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.test-item {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 16px;
}

.test-item h4 {
    margin: 0 0 12px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
}

.image-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.image-item {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 8px;
    background: #f8f9fa;
}

.image-item img {
    width: 100%;
    height: 120px;
    object-fit: cover;
    border-radius: 4px;
    margin-bottom: 8px;
}

.image-info {
    font-size: 12px;
    color: #909399;
    word-break: break-all;
    line-height: 1.4;
}

.log-container {
    margin-top: 16px;
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 12px;
    background: #f8f9fa;
}

.log-item {
    margin-bottom: 8px;
    font-family: monospace;
    font-size: 12px;
}

.log-time {
    color: #909399;
    margin-right: 8px;
}

.log-message {
    color: #606266;
}

.log-item.success .log-message {
    color: #67c23a;
}

.log-item.error .log-message {
    color: #f56c6c;
}
</style>